<template>
  <div class="special-dialog-main">
    <el-button type="primary" @click="handleVisible(true)">特殊商品积分设置</el-button>
    <Dialog :appDialog="appDialog">
      <div>
        <ZwSearchForm :option="searchOption" @search="search" @reset="reset" />
        <ZwTable 
          ref="tableRef" 
          class="table-box" 
          :option="tableOption" 
          :rowKey="getRowKey"
          :paramProp="state.paramProp"
          :fetch-params="state.searchParams" 
          :fetch-api="fetchApi()"
          @updateData="getTableData"
          @select="onSelect"
          @select-all="onSelectAll">
          <template #headerOperateLeft>
            <div class="points-setting" @click="handlerSet">
              批量设置积分
            </div>
          </template>
          <template #headerOperate>
            <div class="gc-content">
              <div class="right">
                <!-- v-auth="'ADD_CROWD_MANAGE'" -->
                <el-button type="primary" @click="handlerAddGoods">添加商品</el-button>
              </div>
            </div>
          </template>
        </ZwTable>
      </div>
    </Dialog>
    <AddGoods ref="addGoodsRef" @submit="addGoodsSave" />
    <ZWDeleteDialog ref="deleteDialogRef" @submit="deleteSubmit" />
  </div>
</template>
<script setup lang="tsx">
import { ref, reactive, computed } from 'vue'
import { deepCopy } from '@/utils/helper'
import { ElMessage, ElButton, ElImage, ElTooltip, ElInput } from 'element-plus';
import { Picture as IconPicture } from '@element-plus/icons-vue'
import { storeList } from '@/api/member/memberList/index'
import { getPointsProductList, delPointsProduct ,setPointsProduct } from '@/api/member/pointsManage/index'
import Dialog from '@/components/Dialog.vue'
import ZWDeleteDialog from '@/components/ZWDeletdialog.vue'
import ZwSearchForm from '@/components/zw/search-form/SearchForm'
import ZwTable from '@/components/zw/table/Table'
import AddGoods from './addGoods.vue'



const tableRef = ref<any>(null)
const deleteDialogRef = ref<any>(null)
const addGoodsRef = ref<any>(null)

const selectionList = reactive<any>([])

const delInfo = reactive<any>({
  id: '',
  product_id: ''
})

const tableList = ref<any>([])

const cancelHandel = () => {
  appDialog.visible = false
}

const submitHandel = async () => {
  // if(!selectionList.length) {
  //   ElMessage.error('请先选择商品')
  //   return
  // }
  console.log(tableList.value,'12333')
  let params = {
    product: tableList.value.map((el: any) => { 
      return { 
        product_id: el.id,
        amount: 1,
        points: el.points,
        shop_id: el.shop_id  
      } 
    })
  }
  let res = await setPointsProduct(params)
  appDialog.visible = false
}

const appDialog = reactive<any>({
  visible: false,
  title: '特殊商品设置',
  width: '60%',
  cancel: cancelHandel,
  submit: submitHandel,
  cancelText: '取消',
  submitText: '确定'
})

const searchOption = computed(() => {
  return [
    {
      label: '商品名称',
      name: 'product_name',
      type: 'input',
      clearable: true,
      placeholder: '请输入商品名称'
    },
    {
      label: '来源店铺',
      shop_name: 'shop_id',
      type: 'select',
      clearable: true,
      placeholder: '请选择来源店铺',
      fetchOptionApi: () => {
        return new Promise((resolve) => {
          storeList({}).then((res: any) => {
            let list: any = [];
            list = res || []
            resolve(list);
          });
        });
      },
      formatOption: (v: any) => ({
        label: v.name,
        value: v.id
      })
    }
  ]
})

const tableOption = [
  {
    type: 'selection',
    width: 60,
    fixed: 'left'
  },
  {
    prop: 'name',
    label: '商品名称',
    width: 150,
    showOverflowTooltip: true,
    render({ row, column, index }: any) {
      const errorSlot = () => (
        <IconPicture />
      )
      return (
        <div class="shop-name">
          <div class="shop-name-img">
            <ElImage class="shop-name-img" vSlots={{error:errorSlot}} src={row.cover}>
            </ElImage>
          </div>
          <div class="shop-name-name">
            <ElTooltip class="box-item" content={row.name} placement="top-start">
              <div>{ row.name }</div>
            </ElTooltip>
          </div> 
        </div>
      )
    }
  },
  {
    prop: 'price',
    label: '价格（元）',
    width: 150,
    render({ row, column, index }: any) {
      return (
        <div>
          {
            row.min_price == row.max_price ? `￥${row.max_price}` : `￥${row.min_price}~￥${row.max_price}`
          }
        </div>
      )
    }
  },
  {
    prop: 'shop_name',
    label: '来源店铺',
    width: 140
  },
  {
    prop: 'points',
    label: '每消费1元赠送积分',
    width: 160,
    render({ row, column, index }: any) {
      return (
        <div>
          <ElInput vModel={row.points} min={1} precision={0} controls={false} class="search_name" placeholder="" />
        </div>
      )
    }
  },
  {
    prop: 'operate',
    label: '操作',
    fixed: 'right',
    width: 120,
    isOperate: true,
    //         authCode: 'PREVIEWGP_QWRUN',
    option: [
      {
        name: '删除',
        click(row: any) {
          handlerDel(row)
        }
      },
    ]
  },
]

const defaultParams = {
  type: 2,
  product_name: '', 
  source: '', 
  shop_name: ''
  
}

const state = reactive({
  searchParams: deepCopy(defaultParams),
  paramProp: { page: 'page', pageSize: 'page_size' }
})

const getRowKey = (row: any) => {
  return row.id
}


const search = (data: any) => {
  tableRef.value.getTable().clearSelection()
  state.searchParams = deepCopy({ ...defaultParams, ...data })
}

const reset = () => {
  tableRef.value.getTable().clearSelection()
  state.searchParams = deepCopy({ ...defaultParams })
}

const fetchApi = () => {
  return getPointsProductList
}
const getTableData = (val?: any) => {
  tableList.value = val || []
  
}

const onSelect = (selection: any, row: any):void => {
  console.log(selection,'1',row)
  selectionList.splice(0)
  selectionList.push(...selection)
}

const onSelectAll = (selection: any):void => {
  console.log(selection,'12')
  selectionList.splice(0)
  selectionList.push(...selection)
}

const handlerDel = (val?: any) => {
  delInfo.id = val.id
  deleteDialogRef.value.content = `确定要删除该商品吗？`
  deleteDialogRef.value.appDialog.visible = true
}

const handlerAddGoods = () => {
  console.log('xxx')
  addGoodsRef.value.appDialog.visible = true
}

const queryList = async () => {
}

const handleVisible = (isVisible = false) => {
  if (!isVisible) {
    tableRef.value.reload()
  }
  appDialog.visible = isVisible;

};

const deleteSubmit = async () => {
  let params = {
    id: delInfo.id,
  }
  let res = await delPointsProduct(params)
  ElMessage.success('删除成功')
  tableRef.value.reload()
}

const handlerSet = async () => {
  if(!selectionList.length) {
    ElMessage.error('请先选择商品')
    return
  }
  let params = {
    product: selectionList.map((el: any) => { 
      return { 
        product_id: el.id,
        amount: 1,
        points: el.points,
        shop_id: el.shop_id  
      } 
    })
  }
  let res = await setPointsProduct(params)
  ElMessage.success('设置成功')
  appDialog.visible = false
}

const addGoodsSave = async () => {
  tableRef.value.reload()
  
}


</script>
<style lang="scss" scoped>
.special-dialog-main {
  .points-setting {
    color: #ff6b00;
    cursor: pointer;
  }
  :deep(.shop-name) {
    display: flex;
    align-items: center;
    .shop-name-img {
      width: 40px;
      height: 40px;
    }
    .shop-name-name {
      margin-left: 4px;
      line-height: 20px;
    }
  }
}
</style>